package org.jeecg.modules.finance.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.finance.entity.FinanceBill;
import org.jeecg.modules.finance.entity.FinanceLabel;
import org.jeecg.modules.finance.service.IFinanceBillService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 财务 - 账单表
 * @Author: jeecg-boot
 * @Date: 2021-05-03
 * @Version: V1.0
 */
@Api(tags = "财务 - 账单表")
@RestController
@RequestMapping("/finance/financeBill")
@Slf4j
public class FinanceBillController extends JeecgController<FinanceBill, IFinanceBillService> {
    @Autowired
    private IFinanceBillService financeBillService;

    /**
     * 分页列表查询
     *
     * @param financeBill
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "财务 - 账单表-分页列表查询")
    @ApiOperation(value = "财务 - 账单表-分页列表查询", notes = "财务 - 账单表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(FinanceBill financeBill,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        financeBill.setCreateBy(sysUser.getId());
        QueryWrapper<FinanceBill> queryWrapper = QueryGenerator.initQueryWrapper(financeBill, req.getParameterMap());
        Page<FinanceBill> page = new Page<FinanceBill>(pageNo, pageSize);
        IPage<FinanceBill> pageList = financeBillService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param financeBill
     * @return
     */
    @AutoLog(value = "财务 - 账单表-添加")
    @ApiOperation(value = "财务 - 账单表-添加", notes = "财务 - 账单表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody FinanceBill financeBill) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        financeBill.setCreateBy(sysUser.getId());
        financeBillService.save(financeBill);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param financeBill
     * @return
     */
    @AutoLog(value = "财务 - 账单表-编辑")
    @ApiOperation(value = "财务 - 账单表-编辑", notes = "财务 - 账单表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody FinanceBill financeBill) {
        financeBillService.updateById(financeBill);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "财务 - 账单表-通过id删除")
    @ApiOperation(value = "财务 - 账单表-通过id删除", notes = "财务 - 账单表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        financeBillService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "财务 - 账单表-批量删除")
    @ApiOperation(value = "财务 - 账单表-批量删除", notes = "财务 - 账单表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.financeBillService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "财务 - 账单表-通过id查询")
    @ApiOperation(value = "财务 - 账单表-通过id查询", notes = "财务 - 账单表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        FinanceBill financeBill = financeBillService.getById(id);
        if (financeBill == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(financeBill);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param financeBill
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, FinanceBill financeBill) {
        return super.exportXls(request, financeBill, FinanceBill.class, "账单 - 标签");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/importExcel/{type}")
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response, @PathVariable String type) {
        System.out.println(type);
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<FinanceBill> list = ExcelImportUtil.importExcel(file.getInputStream(), FinanceBill.class, params);
                //update-begin-author:taoyan date:20190528 for:批量插入数据
                long start = System.currentTimeMillis();
                financeBillService.saveImport(list,type);
                //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
                //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                //update-end-author:taoyan date:20190528 for:批量插入数据
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }


}
